#include <stdio.h>
#include <unistd.h>
#include <time.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"
#include "iot_errno.h"
#include "check_body.h"

#define GPIO_BODY 7

int is_sb = 0; // 定义is_sb
int m_gpio_interrupt_count_before = 0;
int m_gpio_interrupt_count_after = 0;

// 记录GPIO中断次数
void gpio_isr_func(char *arg){
    printf("check Body! Interrupt detected!\n");
    m_gpio_interrupt_count_after++;
}

void gpio_process(){
    osThreadAttr_t attr;
    attr.name = "check_task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 4096;
    attr.priority = 20;
    unsigned int ret;
    
    IoTGpioInit(GPIO_BODY);
    IoTGpioSetDir(GPIO_BODY, IOT_GPIO_DIR_IN);
    ret = IoTGpioRegisterIsrFunc(GPIO_BODY, IOT_INT_TYPE_EDGE, IOT_GPIO_EDGE_RISE_LEVEL_HIGH, gpio_isr_func, NULL);
    if(ret != IOT_SUCCESS){ 
        printf("IotGpioResisterIsrFunc failed(%d)\n",ret);
        return;
    }

    m_gpio_interrupt_count_after = 0;
    IoTGpioSetIsrMask(GPIO_BODY, FALSE);

    while(1){
        printf("*************GPIO Interrupt Example ************");
        printf("gpio interrupt count before = %d\n", m_gpio_interrupt_count_before);
        printf("gpio interrupt count after = %d\n", m_gpio_interrupt_count_after);
        printf("\n");
        if(m_gpio_interrupt_count_after != m_gpio_interrupt_count_before){
            is_sb = 1;
            sleep(10); 
            m_gpio_interrupt_count_before = m_gpio_interrupt_count_after;
            is_sb = 0;
        }
        
        sleep(1); 
    }
}

APP_FEATURE_INIT(gpio_process);